package com.cx.common.secuity.interceptor;

import com.cx.common.core.constant.Constants;
import com.cx.common.core.constant.SecurityConstants;
import com.cx.common.core.context.SecurityContextHolder;
import com.cx.common.core.dto.LoginUserDTO;
import com.cx.common.core.utils.JwtUtils;
import com.cx.common.core.utils.StringUtils;
import com.cx.common.core.utils.uuid.UUID;
import com.cx.common.secuity.auth.AuthUtil;
import com.cx.common.secuity.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author ruoyi
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //注入TraceId，以实现MDC日志跟踪
        String tractId = Optional.ofNullable(MDC.get(Constants.TRACE_ID)).orElse(request.getHeader(Constants.TRACE_ID));
        if (StringUtils.isEmpty(tractId)) {
            tractId = UUID.fastUUID().toString(true);
        }
        MDC.put(Constants.TRACE_ID, tractId);

        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token)) {
            LoginUserDTO loginUser = AuthUtil.getLoginUser(token);
            if (StringUtils.isNotNull(loginUser)) {
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
            }
            //从token解析用户信息，设置到全局信息
            Claims claims = JwtUtils.parseToken(token);
            SecurityContextHolder.setUserId(Long.parseLong(JwtUtils.getUserId(claims)));
            SecurityContextHolder.setUserName(JwtUtils.getUserName(claims));
            SecurityContextHolder.setUserKey(JwtUtils.getUserKey(claims));
            SecurityContextHolder.setSystem(Integer.parseInt(JwtUtils.getSystem(claims)));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SecurityContextHolder.remove();
        MDC.remove(Constants.TRACE_ID);
    }
}
